<!--
 * @Author: chenr 526963089@qq.com
 * @Date: 2023-02-13 10:54:03
 * @LastEditors: chenr 526963089@qq.com
 * @LastEditTime: 2023-02-16 14:35:13
 * @Description: 验证码
-->
<template>
  <a-space>
    <a-input v-model:value="state['Captcha-Code']" placeholder="请输入验证码" />
    <a-spin :indicator="indicator" :spinning="spinning">
      <a-image
        :preview="false"
        style="cursor: pointer"
        alt="点击刷新验证码"
        width="100%"
        height="30px"
        :src="src"
        @click="handleRefresh"
      />
    </a-spin>
  </a-space>
</template>

<script lang="ts" setup>
import { ref, reactive, h, onMounted, watch } from 'vue';
import { getCaptcha } from '@/api/mock/index';
import { LoadingOutlined } from '@ant-design/icons-vue';

export type VerificationType = {
  'Captcha-Key': string; // key
  'Captcha-Code': string; // 图形验证码
};
const state = reactive<VerificationType>({
  'Captcha-Key': '',
  'Captcha-Code': '',
});

/* 自定义输出 */
const emits = defineEmits(['change', 'update:value', 'update:key']);
watch(
  () => state['Captcha-Code'],
  (value) => {
    emits('update:value', value);
  }
);

/* 获取图形验证码 */
const src = ref<string>('');
const spinning = ref<boolean>(false);
const indicator = h(LoadingOutlined, {
  style: {
    fontSize: '18px',
  },
  spin: true,
});
const handleRefresh = async () => {
  try {
    spinning.value = true;
    const res = await getCaptcha();
    src.value = res.image;
    state['Captcha-Key'] = res.key;
    emits('update:key', res.key);
  } finally {
    spinning.value = false;
  }
};
onMounted(() => {
  handleRefresh();
});
</script>

<style scoped lang="less"></style>
